package com.roy.sms.controller;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.roy.sms.service.ArticleService;
import com.roy.sms.service.ColumnService;
import com.roy.sms.util.PageParam;
import com.roy.sms.util.Pager;
import com.roy.sms.vo.ArticleVO;
import com.roy.sms.vo.ColumnVO;

@Controller
public class SiteController extends BaseController{

	@Resource
	private ColumnService columnService;
	
	@Resource
	private ArticleService articleService;

	@RequestMapping("/site/navs.do")
	public void getFrantTopColumn(HttpServletRequest req, HttpServletResponse resp){
		List<ColumnVO> columns = columnService.list(-1);
		req.setAttribute("columns", columns);
		try {
			req.getRequestDispatcher("/WEB-INF/jsp/include/top.jsp").include(req, resp);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/site/bottom.do")
	public void getBottom(HttpServletRequest req, HttpServletResponse resp){
		try {
			req.getRequestDispatcher("/WEB-INF/jsp/include/bottom.jsp").include(req, resp);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/site/login.do")
	public String login(){
		return "login";
	}
	
	@RequestMapping("/site/column.do")
	public String viewColumn(int columnId, ModelMap map, Integer subColumnId,PageParam pageParam){
		List<ColumnVO> columns = columnService.list(columnId);
		map.put("columns", columns);
		ColumnVO c = null;
		Pager<ArticleVO> p = null;
		if(subColumnId == null){
			if(columns.size() > 0){
				c = columns.get(0);
			}
		} else {
			c = columnService.load(subColumnId);
		}
		if(c != null){
			p = articleService.list(pageParam.getRowBeginIndex(), pageParam.getRowCount(), c);
		}
		map.put("page", p);
		map.put("columnId", columnId);
		map.put("subColumnId", subColumnId);
		
		map.put("currPage", pageParam.getPage());
		map.put("totalPage",getTotalPage( p.getTotal() ,pageParam.getRowCount()));
		
		return FORWARD+"/column.jsp";
	}
	
	private int getTotalPage(int total, int pageSize){
		if(total % pageSize == 0){
			return total / pageSize;
		} else {
			return total / pageSize + 1;
		}
	}
	
	
	@RequestMapping("/site/viewArticle.do")
	public String viewArticle(int articleId, ModelMap map){
		map.put("article", articleService.loadArticle(articleId));
		return FORWARD+"/viewArticle.jsp";
	}
	
}
